package com.elminster.common.util;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Collection Utilities
 * 
 * @author Gu
 * @version 1.0
 *
 */
public abstract class CollectionUtil {
	
	/**
	 * Check whether the specified collection is empty
	 * @param collection the specified collection
	 * @return whether the the specified collection is empty
	 */
	public static boolean isEmpty(Collection<?> collection) {
		return null == collection || collection.isEmpty();
	}
	
	/**
	 * Check whether the specified map is empty
	 * @param map the specified map
	 * @return whether the the specified map is empty
	 */
	public static boolean isEmpty(Map<?, ?> map) {
		return null == map || map.isEmpty();
	}

	/**
	 * Convert the specified array to a list which contains all elements in the array
	 * @param array the specified array
	 * @return a list which contains all elements in the array
	 */
	public static List<?> array2List(Object array) {
		return Arrays.asList(ObjectUtil.toObjectArray(array));
	}

	/**
	 * Convert the specified collection to an array which contains all elements in the collection
	 * @param collection the specified collection
	 * @return an array which contains all elements in the collection
	 */
	public static Object collection2Array(Collection<?> collection) {
		if (null == collection) {
			return new Object[0];
		}
		Iterator<?> iterator = collection.iterator();
		Object obj = iterator.next();
		Class<?> clazz = obj.getClass();
		Object[] array = (Object[]) Array.newInstance(clazz, collection.size());
		int i = 0;
		iterator = collection.iterator();
		while (iterator.hasNext()) {
			array[i++] = iterator.next();
		}
		return array;
	}

	/**
	 * Merge an array to specified collection
	 * @param collection specified collection
	 * @param array an array
	 */
	@SuppressWarnings("unchecked")
	public static void mergeArray(Collection collection, Object array) {
		if (null == collection) {
			throw new IllegalArgumentException("Collection can NOT be null.");
		}
		Object[] arr = ObjectUtil.toObjectArray(array);
		for (Object elem : arr) {
			collection.add(elem);
		}
	}
}
